﻿using SIPPaser.Mod;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SIPPaser
{
    /// <summary>
    /// SIP信令解析工具
    /// </summary>
    public  class SIPPaserTool
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg">SIP的字符串</param>
        /// <returns>SIP信令的结构</returns>
        public static SipMessage PaserMsgStr(string msg)    //静态解析
        {
            //判断输入是否是正常
            if (string.IsNullOrEmpty(msg))
                return null;

            SipMessage sipmsg = new SipMessage();

            //解析时间
            //Epoch Time: xxxxxx seconds
            var timestr = GetFiled(msg, "Epoch Time:", " seconds");
            double datetime=-1;
            if (double.TryParse(timestr.Trim(), out datetime))  //判断解析的字符串是否为数字
            {
                sipmsg.Time = GetDateTime(datetime) ;   //转换为具体时间：年月日
            }
            else
                return null;

            //解析消息类型
            //Session Initiation Protocol (BYE)
            var msgtype = GetFiled(msg, "Session Initiation Protocol (", ")");

            //解析消息协议
            //Protocol: UDP
            var msgprot = GetFiled(msg, "Protocol: ", " (1");

            //其他重要信息解析

            //解析消息体
            int startindex = msg.IndexOf("Session Initiation Protocol (");
            if (startindex > 0)
                sipmsg.SIPBody = msg.Substring(startindex, msg.Length - startindex);
            else
                return null;


            return sipmsg;
        }

        /// <summary>
        /// 从start到end取对应的字符串
        /// </summary>
        /// <param name="msg">SIP消息</param>
        /// <param name="start">字段的开头</param>
        /// <param name="end">字段的结尾</param>
        /// <returns>从start到end间的字符串</returns>
        static string GetFiled(string msg,string start,string end)
        {
            int startindex = msg.IndexOf(start);
            int endindex = 0;
            if (startindex > 0)
            {
                endindex = msg.IndexOf(end, startindex);
                if (endindex < startindex)
                    return null;
                startindex += start.Length;//跳过开始
                var timestr = msg.Substring(startindex, endindex - startindex);
                return timestr;
            }
            return null;
        }
        static DateTime GetDateTime(double seconds)
        {
            return new DateTime(1970, 1, 1, 8, 0, 0, DateTimeKind.Utc).AddSeconds(seconds);
        }
    }
}
